from django.shortcuts import render_to_response
import models
import django.http as http
from django.template import Context, loader
from amazonproduct import API
import settings
from django.http import HttpResponseRedirect, HttpResponse
from urlparse import urlsplit
from os.path import basename
import utils
from django.core.urlresolvers import reverse
import forms
from django.utils.html import escape

#-------------------------------------------------------------------------------

def index(request):
    assert False
    book_list = models.Book.objects.all()

    return render_to_response("cds/index.html",{'book_list':book_list})


#-------------------------------------------------------------------------------

def ajax(request):
    assert False
    book_list = models.Book.objects.all()

    return render_to_response("books/index.xml",{'book_list':book_list},mimetype="application/xhtml+xml")

#-------------------------------------------------------------------------------

def search_auto(request):
    search_results_list = []
    if request.method == 'POST':
        api = API(settings.AWS_KEY, settings.SECRET_KEY)
        search = request.REQUEST["search"]
        node = api.item_search('Music', Keywords=search)
        for result in node.Items.Item:
            search_row=[]
            search_row.append(result.ASIN.text)
            search_row.append(result.ItemAttributes.Title)
            try:
                search_row.append(result.ItemAttributes.Creator)
            except:
                search_row.append("")
            search_row.append(result.ItemAttributes.Manufacturer)
            try:
                imagenode = api.item_lookup(result.ASIN.text, ResponseGroup='Images')
                search_row.append(imagenode.Items.Item.MediumImage.URL)
            except:
                search_row.append("")
            search_results_list.append(search_row)
    return shortcuts.render_to_response("cds/auto.html",{"search_results_list":search_results_list})


#-------------------------------------------------------------------------------

def add_auto(request,asin):
    api = API(settings.AWS_KEY, settings.SECRET_KEY)
    try:
        node = api.item_lookup(asin,ResponseGroup='Large')
    except:
        url = reverse ('cds_search_auto')
        return HttpResponseRedirect(url)

    isbn = node.Items.Item.ASIN.text
    try:
        book_list = models.Book.objects.filter(isbn=isbn)
        if len(book_list) != 0:
            url = reverse ('cds_search_auto')
            return HttpResponseRedirect(url)
    except:
        pass
    image=""
    try:
        image=utils.download(node.Items.Item.MediumImage.URL)
    except:
        image=""
    title = node.Items.Item.ItemAttributes.Title.text
    url = str(node.Items.Item.DetailPageURL)
    book = models.Book(
                title=title,
                isbn=isbn,
                condition=0,
                book_type=1,
                copies=1,
                publisher=add_publisher(node.Items.Item.ItemAttributes.Publisher.text),
                image=image,
                amazon_url=url
                )
    book.save()
    for author in node.Items.Item.ItemAttributes.Author:
        abc = str(author)
        try:
            mauthor=models.Author.objects.get(name=abc)
        except:
            mauthor=models.Author(name=abc)
            mauthor.save()

        book.authors.add(mauthor)

    url = reverse ('cds_search_auto')
    return HttpResponseRedirect(url)

#-------------------------------------------------------------------------------

def add_publisher(name):
    try:
        return models.Publisher.objects.get(name=name)
    except:
        models.Publisher(name=name).save()
        return models.Publisher.objects.get(name=name)


#-------------------------------------------------------------------------------

def add_author(request):
    if request.method == 'POST': # If the form has been submitted...
        form = forms.AuthorForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            try:
                newObject = form.save()
            except forms.ValidationError, error:
                newObject = None
            if newObject:
                return HttpResponse('<script type="text/javascript">opener.dismissAddAnotherPopup(window, "%s", "%s");</script>' % \
                    (escape(newObject._get_pk_val()), escape(newObject)))
    else:
        form = forms.AuthorForm() # An unbound form

    return render_to_response('books/add_author.html', {
        'form': form,
    })

#-------------------------------------------------------------------------------

def add_publisher(request):
    if request.method == 'POST': # If the form has been submitted...
        form = forms.PublisherForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            try:
                newObject = form.save()
            except forms.ValidationError, error:
                newObject = None
            if newObject:
                return HttpResponse('<script type="text/javascript">opener.dismissAddAnotherPopup(window, "%s", "%s");</script>' % \
                    (escape(newObject._get_pk_val()), escape(newObject)))
    else:
        form = forms.PublisherForm() # An unbound form

    return render_to_response('books/add_publisher.html', {
        'form': form,
    })

#-------------------------------------------------------------------------------

def add(request):
    if request.method == 'POST': # If the form has been submitted...
        form = forms.BookForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            form.save()
            url = reverse ('cds_mains')
            return HttpResponseRedirect(url)
    else:
        form = forms.BookForm() # An unbound form

    return render_to_response('books/edit.html', {
        'form': form,
    })

#-------------------------------------------------------------------------------

def edit(request,book_id):
    minstance = shortcuts.get_object_or_404(models.Book, id=book_id)
    if request.method == 'POST': # If the form has been submitted...
        form = forms.BookForm(request.POST,instance=minstance) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            form.save()
            url = reverse ('cds_mains')
            return HttpResponseRedirect(url)
    else:
        form = forms.BookForm(instance=minstance) # An unbound form

    return render_to_response('books/edit.html', {
        'form': form,
    })

#-------------------------------------------------------------------------------

